package com.zhan.rkforum.controller;

import com.alibaba.fastjson.JSONObject;
import com.zhan.rkforum.bean.Message;
import com.zhan.rkforum.bean.Page;
import com.zhan.rkforum.bean.User;
import com.zhan.rkforum.service.MessageService;
import com.zhan.rkforum.service.UserService;
import com.zhan.rkforum.util.CommunityConstant;
import com.zhan.rkforum.util.CommunityUtil;
import com.zhan.rkforum.util.HostHolder;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.util.HtmlUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@SuppressWarnings("all")
@RequestMapping("/message")
public class MessageController implements CommunityConstant {

    @Autowired
    private MessageService messageService;

    @Autowired
    private UserService userService;

    @Autowired
    private HostHolder hostHolder;

    @Value("${community.path.address}")
    private String address;

    @Value("${server.servlet.context-path}")
    private String contextPath;


    @GetMapping("/letter")
    public String getConversationPage(Model model, Page page){

        User user = hostHolder.getUser();
        if(ObjectUtils.isEmpty(hostHolder)){
            return "redirect:site/login";
        }

        page.setLimit(5);
        page.setPath(address + contextPath +"/message/letter");
        page.setRows(messageService.selectConversationCount(user.getId()));

        ArrayList<Map<String, Object>> conversations = new ArrayList<>();
        List<Message> messages = messageService.selectConversationByPage(user.getId(), page.getOffset(), page.getLimit());
        for (Message conversation : messages) {
            HashMap<String, Object> map = new HashMap<>();
            map.put("conversation", conversation);
            int conversationUnreadCount = messageService.selectUnreadMessageCount(user.getId(), conversation.getConversationId());
            map.put("unreadCount", conversationUnreadCount);
            int letterCount = messageService.selectLetterCount(conversation.getConversationId());
            map.put("letterCount", letterCount);

            String conversationId = conversation.getConversationId();
            int userId = user.getId();
            String[] ids = conversationId.split("_");
            String from_id = ids[0].equals(String.valueOf(userId)) ? ids[1] : ids[0];
            User fromUser = userService.findUserById(Integer.parseInt(from_id));
            map.put("fromUser", fromUser);
            conversations.add(map);
        }
        model.addAttribute("totalUnreadCount", messageService.selectUnreadMessageCount(user.getId(), null));
        model.addAttribute("conversations", conversations);
        int totalUnRead = messageService.unReadTopicNoticeCount(user.getId(), null);
        totalUnRead = Math.max(totalUnRead, 0);
        model.addAttribute("totalUnReadNotice", totalUnRead);
        return "/site/letter";
    }


    @GetMapping("/letter/detail/{conversationId}")
    public String conversationDetail(Model model, Page page, @PathVariable("conversationId") String conversationId){

        User user = hostHolder.getUser();
        if(ObjectUtils.isEmpty(hostHolder)){
            return "redirect:site/login";
        }

        page.setRows(messageService.selectLetterCount(conversationId));
        page.setPath(address + contextPath +"/message/letter/detail/" + conversationId);
        page.setLimit(5);

        List<Message> messages = messageService.selectLettersByPage(conversationId, page.getOffset(), page.getLimit());

        ArrayList<Map<String, Object>> list = new ArrayList<>();
        if(messages != null){
            for (Message message : messages) {
                HashMap<String, Object> map = new HashMap<>();
                int fromId = message.getFromId();
                User fromUser = userService.findUserById(fromId);
                map.put("fromUser", fromUser);
                map.put("message", message);
                list.add(map);
            }
        }

        model.addAttribute("letters", list);

        int userId = user.getId();
        String[] ids = conversationId.split("_");
        String targetId = ids[0].equals(String.valueOf(userId)) ? ids[1] : ids[0];
        User targetUser = userService.findUserById(Integer.parseInt(targetId));

        model.addAttribute("targetUser", targetUser);
        //已阅读，批量更新消息状态
        List<Integer> updateIds = getUpdateLetters(messages);
        messageService.updateMessagesStatus(updateIds, 1);

        return "site/letter-detail";
    }

    private List<Integer> getUpdateLetters(List<Message> messages){
        ArrayList<Integer> ids = new ArrayList<>();
        if(ObjectUtils.isNotEmpty(messages)){
            for (Message message : messages) {
                if(message.getFromId() != hostHolder.getUser().getId() && message.getStatus() == 0){
                    ids.add(message.getId());
                }
            }
        }
        return ids;
    }

    @ResponseBody
    @PostMapping("/letter/send")
    public String sendLetter(String toName, String content){
        User toUser = userService.findUserByName(toName);
        int toId = toUser.getId();
        int fromId = hostHolder.getUser().getId();
        try {
            messageService.addMessage(fromId, toId, content);
        }catch (Exception e) {
            return CommunityUtil.getJsonString(ADD_MESSAGE_FAILURE, "发送失败");
        }
        return CommunityUtil.getJsonString(ADD_MESSAGE_SUCCESS, "发送成功");
    }

    @GetMapping("/notice")
    public String getNotice(Model model){
        User user = hostHolder.getUser();
        //评论通知
        HashMap<String, Object> commentMap = new HashMap<>();
        int commentCount = messageService.findTopicNoticeCount(user.getId(), TOPIC_COMMENT);
        Message comment = messageService.findNoticeById(user.getId(), TOPIC_COMMENT);
        if(comment != null){
            int unreadCommentCount = messageService.unReadTopicNoticeCount(user.getId(), TOPIC_COMMENT);
            commentMap.put("commentCount", commentCount);
            commentMap.put("comment", comment);
            String data = comment.getContent();
            data = HtmlUtils.htmlUnescape(data);
            HashMap<String, Object> hashMap = JSONObject.parseObject(data, HashMap.class);
            //存入对方的信息
            commentMap.put("user", userService.findUserById((Integer) hashMap.get("userId")));
            commentMap.put("entityType", hashMap.get("entityType"));
            commentMap.put("entityId", hashMap.get("entityId"));
            commentMap.put("postId", hashMap.get("postId"));
            commentMap.put("count", commentCount);
            commentMap.put("unreadCount", unreadCommentCount);
            model.addAttribute("commentNotice", commentMap);
        }
        //点赞通知
        HashMap<String, Object> likeMap = new HashMap<>();
        int likeCount = messageService.findTopicNoticeCount(user.getId(), TOPIC_LIKE);
        Message like = messageService.findNoticeById(user.getId(), TOPIC_LIKE);
        if(like != null){
            int unreadLikeCount = messageService.unReadTopicNoticeCount(user.getId(), TOPIC_LIKE);
            likeMap.put("likeCount", likeCount);
            likeMap.put("like", like);
            String data = HtmlUtils.htmlUnescape(like.getContent());
            HashMap<String, Object> hashMap = JSONObject.parseObject(data, HashMap.class);
            //存入对方的信息
            likeMap.put("user", userService.findUserById((Integer) hashMap.get("userId")));
            likeMap.put("entityType", hashMap.get("entityType"));
            likeMap.put("entityId", hashMap.get("entityId"));
            likeMap.put("postId", hashMap.get("postId"));
            likeMap.put("count", likeCount);
            likeMap.put("unreadCount", unreadLikeCount);
            model.addAttribute("likeNotice", likeMap);
        }

        //关注通知
        HashMap<String, Object> followMap = new HashMap<>();
        int followCount = messageService.findTopicNoticeCount(user.getId(), TOPIC_FOLLOW);
        Message follow = messageService.findNoticeById(user.getId(), TOPIC_FOLLOW);
        if(follow != null){
            int unreadFollowCount = messageService.unReadTopicNoticeCount(user.getId(), TOPIC_FOLLOW);
            followMap.put("follow", follow);
            String data = HtmlUtils.htmlUnescape(follow.getContent());
            HashMap<String, Object> hashMap = JSONObject.parseObject(data, HashMap.class);
            //存入对方的信息
            followMap.put("followCount", followCount);
            followMap.put("user", userService.findUserById((Integer) hashMap.get("userId")));
            followMap.put("entityType", hashMap.get("entityType"));
            followMap.put("entityId", hashMap.get("entityId"));
            followMap.put("postId", hashMap.get("postId"));
            followMap.put("count", followCount);
            followMap.put("unreadCount", unreadFollowCount);
            model.addAttribute("followNotice", followMap);
        }
        int totalUnRead = messageService.unReadTopicNoticeCount(user.getId(), null);
        totalUnRead = Math.max(totalUnRead, 0);
        model.addAttribute("totalUnreadCount", messageService.selectUnreadMessageCount(user.getId(), null));
        model.addAttribute("totalUnRead", totalUnRead);


        return "/site/notice";
    }


    @GetMapping("/notice/detail/{topic}")
    public String getNoticeList(@PathVariable("topic") String topic, Page page, Model model){
        User user = hostHolder.getUser();
        page.setLimit(5);
        page.setPath("/message/notice/detail/" + topic);
        page.setRows(messageService.findTopicNoticeCount(user.getId(), topic));
        List<Message> messageList = messageService.findMessageList(user.getId(), topic, page.getOffset(), page.getLimit());
        List<Map<String, Object>> maps = new ArrayList<>();
        if(messageList != null){
            for (Message message : messageList) {
                HashMap<String, Object> map = new HashMap<>();
                String data = HtmlUtils.htmlUnescape(message.getContent());
                HashMap dataMap = JSONObject.parseObject(data, HashMap.class);
                map.put("message",message);
                map.put("user", userService.findUserById((Integer) dataMap.get("userId")));
                map.put("entityId", dataMap.get("entityId"));
                map.put("entityType", dataMap.get("entityType"));
                map.put("postId", dataMap.get("postId"));

                User fromUser = userService.findUserById(message.getFromId());
                map.put("fromUser", fromUser);
                maps.add(map);
            }
        }
        model.addAttribute("noticeList", maps);
        //设置已读
        List<Integer> ids = getUpdateLetters(messageList);
        if(! ids.isEmpty()){
            messageService.updateMessagesStatus(ids, 1);
        }
        return "site/notice-detail";
    }


}
